﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;

namespace Gw2MumbleLinkServer
{
    public partial class formMain : Form
    {
        private const string REG_KEY = "Gw2MumbleLinkServer";
        private bool runOnStartup;

        public formMain(ushort port)
        {
            InitializeComponent();

            textPort.Text = port.ToString();
            checkRunOnStartup.Checked = runOnStartup = WindowsStartup.Exists(REG_KEY);

            bool alreadyRunning = false;

            try
            {
                alreadyRunning = IsAlreadyRunning();
            }
            catch { }

            buttonStart.Visible = !alreadyRunning;
            buttonStop.Visible = alreadyRunning;
            labelAlreadyRunning.Visible = alreadyRunning;
        }

        public ushort Port
        {
            get;
            private set;
        }

        private bool IsAlreadyRunning()
        {
            Process[] processes = Process.GetProcessesByName("Gw2MumbleLinkServer");
            Process current = Process.GetCurrentProcess();

            foreach (Process p in processes)
            {
                try
                {
                    if (p.Id != current.Id && p.MainModule.FileName == current.MainModule.FileName)
                        return true;
                }
                catch { }
            }

            return false;
        }

        private void textPort_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = !Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar);
        }

        private void formMain_Load(object sender, EventArgs e)
        {

        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            buttonStart.Enabled = false;

            ushort port = Server.DEFAULT_PORT;
            UInt16.TryParse(textPort.Text, out port);

            if (checkRunOnStartup.Checked)
            {
                try
                {
                    UInt16.TryParse(textPort.Text, out port);

                    WindowsStartup.Add(REG_KEY, Application.ExecutablePath, "-silent -port " + port);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Unable to create registry key.\n\n" + ex.Message, "An error has occured", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    buttonStart.Enabled = true;
                    return;
                }
            }
            else if (WindowsStartup.Exists(REG_KEY))
            {
                try
                {
                    WindowsStartup.Remove(REG_KEY);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Unable to remove registry key.\n\n" + ex.Message, "An error has occured", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            this.Port = port;
            this.DialogResult = DialogResult.OK;
        }

        private void formMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing && runOnStartup && !checkRunOnStartup.Checked)
            {
                try
                {
                    WindowsStartup.Remove(REG_KEY);
                }
                catch { }
            }
        }

        private void buttonStop_Click(object sender, EventArgs e)
        {
            buttonStop.Enabled = false;

            Process[] processes = Process.GetProcessesByName("Gw2MumbleLinkServer");
            Process current = Process.GetCurrentProcess();

            foreach (Process p in processes)
            {
                try
                {
                    if (p.Id != current.Id && p.MainModule.FileName == current.MainModule.FileName)
                    {
                        try
                        {
                            p.Kill();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Unable to stop the process.\n\n" + ex.Message, "An error has occured", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
                catch { }
            }

            buttonStop.Visible = false;
            buttonStart.Visible = true;
            labelAlreadyRunning.Visible = false;
        }
    }
}
